<template>
  <div class="version-panel">
    <div class="panel-header">
      <div class="panel-title">版本历史</div>
      <el-button
        type="primary"
        size="small"
        @click="showSaveDialog = true"
      >
        保存版本
      </el-button>
    </div>

    <div class="version-list">
      <el-timeline>
        <el-timeline-item
          v-for="version in versions"
          :key="version.id"
          :timestamp="formatDate(version.created_at)"
          :type="version.id === currentVersionId ? 'primary' : ''"
        >
          <div class="version-item">
            <div class="version-info">
              <div class="version-number">{{ version.version_number }}</div>
              <div class="version-comment">{{ version.comment }}</div>
            </div>
            <div class="version-actions">
              <el-button-group size="small">
                <el-button
                  type="primary"
                  :disabled="version.id === currentVersionId"
                  @click="handleSwitch(version)"
                >
                  切换
                </el-button>
                <el-button
                  v-if="version.id !== currentVersionId"
                  type="info"
                  @click="handleCompare(version)"
                >
                  对比
                </el-button>
              </el-button-group>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!-- 保存版本对话框 -->
    <el-dialog
      v-model="showSaveDialog"
      title="保存版本"
      width="500px"
    >
      <el-form
        ref="versionFormRef"
        :model="versionForm"
        :rules="versionRules"
        label-width="100px"
      >
        <el-form-item label="版本号" prop="version_number">
          <el-input
            v-model="versionForm.version_number"
            placeholder="请输入版本号"
          />
        </el-form-item>
        <el-form-item label="版本说明" prop="comment">
          <el-input
            v-model="versionForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入版本说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSaveDialog = false">取消</el-button>
          <el-button
            type="primary"
            :loading="saving"
            @click="handleSaveVersion"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 版本对比对话框 -->
    <el-dialog
      v-model="showCompareDialog"
      title="版本对比"
      width="800px"
    >
      <div class="version-compare">
        <div class="compare-header">
          <div class="current-version">
            <div class="version-title">当前版本</div>
            <div class="version-number">{{ currentVersion?.version_number }}</div>
          </div>
          <div class="compare-version">
            <div class="version-title">对比版本</div>
            <div class="version-number">{{ compareVersion?.version_number }}</div>
          </div>
        </div>
        <div class="compare-content">
          <el-tabs v-model="compareTab">
            <el-tab-pane label="节点变更" name="nodes">
              <div class="diff-list">
                <div
                  v-for="(diff, index) in nodeDiffs"
                  :key="index"
                  class="diff-item"
                  :class="diff.type"
                >
                  <el-icon>
                    <Plus v-if="diff.type === 'added'" />
                    <Minus v-if="diff.type === 'removed'" />
                    <Edit v-if="diff.type === 'modified'" />
                  </el-icon>
                  <span>{{ getDiffText(diff) }}</span>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="连线变更" name="edges">
              <div class="diff-list">
                <div
                  v-for="(diff, index) in edgeDiffs"
                  :key="index"
                  class="diff-item"
                  :class="diff.type"
                >
                  <el-icon>
                    <Plus v-if="diff.type === 'added'" />
                    <Minus v-if="diff.type === 'removed'" />
                    <Edit v-if="diff.type === 'modified'" />
                  </el-icon>
                  <span>{{ getDiffText(diff) }}</span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Minus, Edit } from '@element-plus/icons-vue'
import { NODE_LABELS } from './NodeTypes'

const props = defineProps({
  processId: {
    type: [String, Number],
    required: true
  },
  currentVersionId: {
    type: Number,
    default: null
  },
  onVersionSwitch: {
    type: Function,
    required: true
  },
  onVersionSave: {
    type: Function,
    required: true
  }
})

const versions = ref([])
const showSaveDialog = ref(false)
const showCompareDialog = ref(false)
const saving = ref(false)
const compareTab = ref('nodes')
const compareVersion = ref(null)
const nodeDiffs = ref([])
const edgeDiffs = ref([])

const versionForm = ref({
  version_number: '',
  comment: ''
})

const versionRules = {
  version_number: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { pattern: /^\d+\.\d+\.\d+$/, message: '版本号格式为：x.y.z', trigger: 'blur' }
  ],
  comment: [
    { required: true, message: '请输入版本说明', trigger: 'blur' }
  ]
}

const versionFormRef = ref(null)

// 当前版本
const currentVersion = computed(() => {
  return versions.value.find(v => v.id === props.currentVersionId)
})

// 加载版本列表
const loadVersions = async () => {
  try {
    const response = await fetch(`http://localhost:8000/api/process/${props.processId}/versions`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error('获取版本列表失败')
    }
    
    const data = await response.json()
    versions.value = data.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
  } catch (error) {
    console.error('获取版本列表失败:', error)
    ElMessage.error(error.message || '获取版本列表失败')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 切换版本
const handleSwitch = async (version) => {
  try {
    await props.onVersionSwitch(version)
    ElMessage.success('切换版本成功')
  } catch (error) {
    console.error('切换版本失败:', error)
    ElMessage.error(error.message || '切换版本失败')
  }
}

// 保存版本
const handleSaveVersion = async () => {
  if (!versionFormRef.value) return
  
  await versionFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        await props.onVersionSave(versionForm.value)
        showSaveDialog.value = false
        ElMessage.success('保存版本成功')
        await loadVersions()
      } catch (error) {
        console.error('保存版本失败:', error)
        ElMessage.error(error.message || '保存版本失败')
      } finally {
        saving.value = false
      }
    }
  })
}

// 对比版本
const handleCompare = async (version) => {
  compareVersion.value = version
  showCompareDialog.value = true
  await compareVersions(currentVersion.value, version)
}

// 计算版本差异
const compareVersions = async (current, target) => {
  // 重置差异数据
  nodeDiffs.value = []
  edgeDiffs.value = []
  
  const currentData = current.data
  const targetData = target.data
  
  // 比较节点
  const currentNodes = new Map(currentData.nodes.map(node => [node.id, node]))
  const targetNodes = new Map(targetData.nodes.map(node => [node.id, node]))
  
  // 查找新增和修改的节点
  targetNodes.forEach((node, id) => {
    if (!currentNodes.has(id)) {
      nodeDiffs.value.push({
        type: 'added',
        node: node
      })
    } else {
      const currentNode = currentNodes.get(id)
      if (JSON.stringify(currentNode) !== JSON.stringify(node)) {
        nodeDiffs.value.push({
          type: 'modified',
          oldNode: currentNode,
          newNode: node
        })
      }
    }
  })
  
  // 查找删除的节点
  currentNodes.forEach((node, id) => {
    if (!targetNodes.has(id)) {
      nodeDiffs.value.push({
        type: 'removed',
        node: node
      })
    }
  })
  
  // 比较连线
  const currentEdges = new Map(currentData.edges.map(edge => [edge.id, edge]))
  const targetEdges = new Map(targetData.edges.map(edge => [edge.id, edge]))
  
  // 查找新增和修改的连线
  targetEdges.forEach((edge, id) => {
    if (!currentEdges.has(id)) {
      edgeDiffs.value.push({
        type: 'added',
        edge: edge
      })
    } else {
      const currentEdge = currentEdges.get(id)
      if (JSON.stringify(currentEdge) !== JSON.stringify(edge)) {
        edgeDiffs.value.push({
          type: 'modified',
          oldEdge: currentEdge,
          newEdge: edge
        })
      }
    }
  })
  
  // 查找删除的连线
  currentEdges.forEach((edge, id) => {
    if (!targetEdges.has(id)) {
      edgeDiffs.value.push({
        type: 'removed',
        edge: edge
      })
    }
  })
}

// 获取差异文本描述
const getDiffText = (diff) => {
  if (diff.type === 'added') {
    if (diff.node) {
      return `新增节点: ${NODE_LABELS[diff.node.type]} (${diff.node.text?.value || ''})`
    } else {
      return `新增连线: ${diff.edge.sourceNodeId} -> ${diff.edge.targetNodeId}`
    }
  } else if (diff.type === 'removed') {
    if (diff.node) {
      return `删除节点: ${NODE_LABELS[diff.node.type]} (${diff.node.text?.value || ''})`
    } else {
      return `删除连线: ${diff.edge.sourceNodeId} -> ${diff.edge.targetNodeId}`
    }
  } else {
    if (diff.oldNode && diff.newNode) {
      return `修改节点: ${NODE_LABELS[diff.oldNode.type]} (${diff.oldNode.text?.value || ''} -> ${diff.newNode.text?.value || ''})`
    } else {
      return `修改连线: ${diff.oldEdge.sourceNodeId} -> ${diff.oldEdge.targetNodeId}`
    }
  }
}

// 初始化
onMounted(() => {
  loadVersions()
})
</script>

<style lang="scss" scoped>
.version-panel {
  width: 300px;
  padding: 20px;
  border-left: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .panel-title {
      font-size: 16px;
      font-weight: 500;
    }
  }
  
  .version-list {
    flex: 1;
    overflow-y: auto;
    
    .version-item {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 8px;
      
      .version-info {
        flex: 1;
        margin-right: 16px;
        
        .version-number {
          font-weight: 500;
          margin-bottom: 4px;
        }
        
        .version-comment {
          color: #666;
          font-size: 13px;
        }
      }
    }
  }
}

.version-compare {
  .compare-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 4px;
    
    .version-title {
      font-weight: 500;
      margin-bottom: 8px;
    }
    
    .version-number {
      color: #409EFF;
    }
  }
  
  .diff-list {
    .diff-item {
      display: flex;
      align-items: center;
      padding: 8px;
      border-radius: 4px;
      margin-bottom: 4px;
      
      &.added {
        background-color: #f0f9eb;
        color: #67c23a;
      }
      
      &.removed {
        background-color: #fef0f0;
        color: #f56c6c;
      }
      
      &.modified {
        background-color: #ecf5ff;
        color: #409eff;
      }
      
      .el-icon {
        margin-right: 8px;
      }
    }
  }
}
</style> 